package com.zzvcom.doc.html;



public class SafeCssLinePrefixer {

    /**
     * 目前没有搞定太多就处理这些
     * org.docx4j.convert.out.html.
     * private static Element createStyleElement(HTMLConversionContext conversionContext, Document document, StringBuilder buffer) {
     * 目前也是一个样式，一行，还是可以使用
     * @param css
     * @param prefix
     * @return
     * @throws Exception
     */
    public static String prefixCssClassesPreserveValue(String css, String prefix) {
        String[] split = css.split("\n");
        StringBuilder result = new StringBuilder();
        for (String s : split) {
            if(s.startsWith("@media")){
                result.append(s).append("\n");
            }
            else if(s.startsWith(".")){
              result.append(".").append(prefix).append(s.substring(1)).append("\n");
            }
            else {
                int i = s.indexOf("{");
                if(i > 0){
                    String start = s.substring(0, i);
                    String end = s.substring(i);
                    String[] split1 = start.split("\\.");
                    if(split1.length==2){
                        StringBuilder sb = new StringBuilder();
                        sb.append(split1[0]).append(".").append(prefix).append(split1[1]);
                        result.append(sb).append(end).append("\n");
                    }else{
                        result.append(s).append("\n");
                    }
                }else {
                    result.append(s).append("\n");
                }
            }


        }
        return result.toString();

    }
    public static void main(String[] args) throws Exception {
        String css = "table.abc { display: table; font-size: 12.5pt; }\n" +
                ".docDefaults { margin: 0; }\n" +
                ".123-BR { text-align: justify; }\n" +
                "@media print { .print { display: none; } }";

        String prefixedCss = prefixCssClassesPreserveValue(css, "doc1-");
        System.out.println(prefixedCss);
    }
}